<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Jobs\PublishLotteryJob;
use App\Jobs\PublishLotteryStartJob;
use App\Models\Circle;
use App\Models\Notification;
use App\Models\Subscribe;
use App\Models\User;
use App\Models\UserJoinCircle;
use App\Mongo\CircleMon;
use App\Services\NotifyService;
use App\Services\PublishTemplateService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use YangJiSen\CacheUserProvider\CacheForget;

class CircleController extends BaseController
{
    protected $model = Circle::class;

    public function index(Request $request) {
        $input = $request->input();
        $search = ['start_at' => '', 'end_at' => '', 'status' => '2', 'title' => ''];
        $nickname = $request->input('nickname');
        $is_activity = $request->input('is_activity', 0);
        $activity_start_at = $request->input('activity_start_at');
        $activity_end_at = $request->input('activity_end_at');
        $category_ids = $request->input('category_ids');
        $not_tag_cat = $request->input('not_tag_cat');
        $arr_category_id = explode(",", $category_ids);
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');

        if ($is_activity)
            $search['status'] = 0;

        $list = Circle::apply($search, $input)->when($nickname, function ($q) use($nickname) {
            $q->whereHas('user', function ($qr) use($nickname) {
                $qr->where('nickname', 'like', '%' . $nickname . '%');
            });
            })->when($activity_start_at, function ($q) use($activity_start_at) {
                $q->where('activity_start_at', '>', $activity_start_at);
            })->when($activity_end_at, function ($q) use($activity_end_at) {
                $activity_end_at = date('Y-m-d', strtotime($activity_end_at) + 24 * 3600);
                $q->where('activity_end_at', '<', $activity_end_at);
            })->withCertain('user', ['nickname'])
            ->with(['circle_category' => function($q) {
                $q->select('*');
            }])
            ->when(!empty($arr_category_id[0]), function ($q) use($arr_category_id) {
                $q->whereHas('circle_category', function ($qr) use($arr_category_id) {
                    $qr->whereIn('circle_category.id', $arr_category_id);
                });
            })
            ->when($not_tag_cat, function ($q) {
                $q->whereNotExists(function ($q) {
                    $q->select(\DB::raw(1))->from('circle_category_relates')->whereRaw('circles.id = circle_category_relates.circle_id');
                });
            })
            ->withCount(['article_yesterday' => function($q) {
                $start_at = date("Y-m-d 00:00:01",strtotime("-1 day"));
                $end_at = date("Y-m-d 23:59:59",strtotime("-1 day"));
                $q->where('articles.created_at', '>=', $start_at)->where('articles.created_at', '<=', $end_at);
            }])->where('is_activity', $is_activity)
            ->orderBy($order_by_key, $order_by_value)
            ->paginate(per_page());
//        foreach ($list as $item) {
//            $item->append('activity_status');
//        }

        return $this->paginate($list);
    }

    public function info(Request $request)
    {
        $this->validate($request, [
            'id' => 'required'
        ]);
        $user_id = $this->getUserId();
        $id = $request->input('id');
        $info = Circle::with(['user' => function($q) {
                $q->select('id','nickname', 'weixin', 'avatar_url');
            }, 'user.animal' => function($q) {
                $q->select('user_id', 'title', 'birthday', 'category_title');
            }])
            ->withCount(['is_focus' => function($q) use($user_id){
                $q->where('user_id', $user_id);
            }])->find($id);
        if (!$info)
            return $this->failed('圈子不存在');

        return $this->success($info);
    }


    public function setCategory(Request $request) {
       $this->validate($request, [
           'ids' => 'required',
           'category_ids' => 'required',
       ]);
       $input = $request->input();
       $arr_id = explode(",", $input['ids']);
       $arr_category_id = explode(",", $input['category_ids']);
       foreach ($arr_id as $id) {
           $circle = Circle::find($id);
           if (in_array(1, $arr_category_id)) {
               //地域
               $circle->is_area = 1;
           } else
               $circle->is_area = 0;
           $circle->save();
           $circle->circle_category()->sync($arr_category_id);
       }
       return $this->success([]);
    }

    public function storeActivity(Request $request)
    {
        $this->validate($request, [
            'user_id' => 'required',
            'title' => 'required',
            'desc' => 'required',
            'logo' => 'required',
            'activity_start_at' => 'required',
            'activity_end_at' => 'required',
        ]);
        $input = $request->input();
        $input['is_activity'] = 1;
        $input['status'] = Circle::STATUS_SUCCESS;
        $id = \request("id");
        if ($id) {
            $one = Circle::find($id);
            if (!$one) {
                return $this->failed('ID不存在');
            }
            $one->update($input);
        } else {
            $info = Circle::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function destroy(Request $request)
    {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        try {
            return \DB::transaction(function () use($ids) {
                $arr_id = explode(",", $ids);
                foreach ($arr_id as $id) {
                    $list = UserJoinCircle::where('circle_id', $id)->get();
                    $info = $this->model::find($id);
                    foreach ($list as $key => $item) {
                        if ($info->status == Circle::STATUS_SUCCESS) {
                            $user = User::where('id', $item->user_id)->first();
                            if ($user) {
                                $user->circle_count -= 1;
                                if ($user->circle_count >= 0) {
                                    $user->save();
                                    CacheForget::CacheForget($user);
                                }

                            }
                        }
                        $item->delete();
                    }
                    if (!$info->is_activity) {
                        $circleMon = CircleMon::where('id', intval($id))->first();
                        $circleMon->delete();
                    }
                    $info->delete();
                }
                return $this->success([]);
            });
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->failed($e->getMessage());
        }
    }

    public function _after_editStatus($item, $action, $value, $reason) {
        if ($action == 'audit' ) {
            if ($value == 3) {
                $title = "圈子审核不通过";
                $reason = '尊敬的用户您好，您创建的圈子："'.$item->title.'"因"'.$reason.'"而审核不通过，请您再次创建并提交';
                NotifyService::store(0, Notification::TYPE_SYSTEM, $item->id, $item->user_id, $reason, 0, $title);
            } else if($value == 2) {
                $title = '圈子审核通过';
                $reason = '您申请创建的圈子‘'.$item->title.'’，已通过审核，请在我家-圈子查看';
                NotifyService::store(0, Notification::TYPE_SYSTEM, $item->id, $item->user_id, $reason, 0, $title);

                $user = User::where('id', $item->user_id)->first();
                if ($user) {
                    $user->circle_count += 1;
                    $user->save();
                }
            }
            CircleMon::where('id', $item->id)->update([
                'status' => $value
            ]);
        }
    }

    public function editStatus(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'value' => 'required',
        ]);
        $value = \request('value');
        $action = \request('action');
        $reason = \request('reason', '');
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);

        $list = $this->model::whereIn('id', $arr_id)->get();
        foreach ($list as $item) {
            if ($action == 'audit') {
                $item->status = $value;
                $item->remark = $reason;
            } elseif ($action == 'black') {
                $item->is_black = $value;
                $item->reason = $reason;
            } elseif ($action == 'vip') {
                $item->is_vip = $value;
            } else if($action == 'sort') {
                $item->sort = $value;
            } else if($action == 'is_hot_activity') {
                if ($value == 1)
                    Circle::where('is_hot_activity', 1)->update(['is_hot_activity'=> 0]);
                $item->is_hot_activity = $value;
            } else if($action == 'on_status') {
                $item->on_status = $value;
            }
            if ($item->save()) {
                if (method_exists($this, '_after_editStatus')) {
                    $this->_after_editStatus($item, $action, $value, $reason);
                }
            }
        }
        return $this->success([]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'id' => 'required'
        ]);
        $input = $request->input();
        $title = $request->input('title');
        $id = \request('id');
        $user_id = $request->input('user_id');
        $circle = Circle::find($id);
        if (!$circle)
            return $this->failed('圈子不存在');
        $exist_id = Circle::where('title', $title)->value('id');
        if ($id) {
            if ($exist_id && $id != $exist_id)
                return $this->failed('圈子已经存在');
        }
        if ($circle->user_id != $user_id) {
            $userJoinCircle = UserJoinCircle::where('user_id', $user_id)->where('circle_id', $id)->first();
            if (!$userJoinCircle) {
                UserJoinCircle::create([
                    'user_id' => $user_id,
                    'circle_id' => $id,
                    'is_owner' => 1,
                    'is_activity' => $circle->is_activity
                ]);
                $user = User::find ($user_id);
                $user->circle_count += 1;
                $user->save();
                CacheForget::CacheForget($user);

                $circle->join_count += 1;
                $circle->save();

            } else {
                $userJoinCircle->is_owner = 1;
                $userJoinCircle->save();
            }
            UserJoinCircle::where('user_id', $circle->user_id)->where('circle_id', $id)->update([
                'is_owner' => 0
            ]);
        }
        Circle::where('id', $id)->update($input);
        return $this->success([]);
    }

    public function publishActivityLottery(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'lottery' => 'required',
        ]);
        $id = \request('id');
        $lottery = \request('lottery');
        $circle = Circle::find($id);
        if (!$circle || !$circle->is_activity)
            return $this->failed('活动不存在');

        if (strtotime($circle->activity_end_at) > time()) {
            return $this->failed('当前活动未截止');
        }
        $is_dispatch_job = $circle->is_publish_result;

        $circle->lottery = $lottery;
        $circle->is_publish_result = 1;
        $circle->save();

        if (!$is_dispatch_job)
            $this->dispatch(new PublishLotteryJob($id));

        Cache::forget(Circle::CACHE_CIRCLE_LOTTERY_USER . '_' . $id);
        return $this->success([]);
    }

    public function pushActivityStartTemplate(Request $request) {
        $this->validate($request, [
            'id' => 'required',
        ]);
        $id = \request('id');
        $activity_item = Circle::find($id);
        if (!$activity_item || !$activity_item->is_activity)
            return $this->failed('活动不存在');

        $this->dispatch(new PublishLotteryStartJob($id));
        return $this->success([]);
    }

}

